﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.Remoting.Contexts;

namespace SampleCode.VirtualFS
{
    //TODO: implement parameter checks and exceptions
    
    /// <summary>
    /// A synchronized FileStream
    /// </summary>
    [Synchronization]
    internal class FsSyncFileStream : ContextBoundObject, IDisposable
    {
        /// <summary>
        /// Stream to read/write the physical file
        /// </summary>
        private Stream _physicalStream;

        /// <summary>
        /// File metadata
        /// </summary>
        internal FsInternalFileInfo FileInfo { get; private set;}

        private LinkedListNode<FsInternalFileInfo> _fileNode;
        /// <summary>
        /// A file node from the linked list. Getting it from the list takes O(total_file_count), but fortunately the node is only necessary when reorganizing the file
        /// </summary>
        private LinkedListNode<FsInternalFileInfo> FileNode
        {
            get
            {
                return _fileNode ?? (_fileNode = _fileTable.FileList.Find(FileInfo));
            }
        }

        /// <summary>
        /// File system table 
        /// </summary>
        private FsFileTable _fileTable;

        public FsSyncFileStream(Stream physicalStream, FsInternalFileInfo fileInfo, FsFileTable fileTable, bool isForWriting)
        {
            // checking if the file is not open already
            if (!fileInfo.Block(isForWriting))
                throw new UnauthorizedAccessException("The file is already open");

            _physicalStream  = physicalStream;
            FileInfo         = fileInfo;
            _fileTable       = fileTable;
        }

        ~FsSyncFileStream()
        {
            Dispose(false);
        }

        /// <summary>
        /// Clears all buffers for this stream and causes any buffered data to be written to the underlying device.
        /// </summary>
        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
        public void Flush()
        {
            _physicalStream.Flush();
        }

        /// <summary>
        /// Reads a sequence of bytes from the current stream and advances the position within the stream by the number of bytes read.
        /// </summary>
        /// <returns>
        /// The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.
        /// </returns>
        /// <param name="buffer">An array of bytes. When this method returns, the buffer contains the specified byte array with the values between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced by the bytes read from the current source. </param>
        /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream. </param>
        /// <param name="count">The maximum number of bytes to be read from the current stream. </param>
        /// <exception cref="T:System.ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is larger than the buffer length. </exception>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="buffer"/> is null. </exception>
        /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="offset"/> or <paramref name="count"/> is negative. </exception>
        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
        /// <exception cref="T:System.NotSupportedException">The stream does not support reading. </exception>
        /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
        public int Read(byte[] buffer, int offset, int count)
        {
            if(!FileInfo.IsOpenForReading)
            {
                throw new NotSupportedException("The stream does not support reading.");
            }

            // checking length
            if (count > Length - Position)
            {
                count = Length - Position;
            }

            // performing physical read
            _physicalStream.Position = _fileTable.DataStartOffset + FileInfo.Start + Position;
            int res = _physicalStream.Read(buffer, offset, count);

            Position += res;
            return res;
        }

        /// <summary>
        /// When overridden in a derived class, writes a sequence of bytes to the current stream and advances the current position within this stream by the number of bytes written.
        /// </summary>
        /// <param name="buffer">An array of bytes. This method copies <paramref name="count"/> bytes from <paramref name="buffer"/> to the current stream. </param>
        /// <param name="offset">The zero-based byte offset in <paramref name="buffer"/> at which to begin copying bytes to the current stream. </param>
        /// <param name="count">The number of bytes to be written to the current stream. </param>
        /// <exception cref="T:System.ArgumentException">The sum of <paramref name="offset"/> and <paramref name="count"/> is greater than the buffer length. </exception>
        /// <exception cref="T:System.ArgumentNullException"><paramref name="buffer"/> is null. </exception>
        /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="offset"/> or <paramref name="count"/> is negative. </exception>
        /// <exception cref="T:System.IO.IOException">An I/O error occurs. </exception>
        /// <exception cref="T:System.NotSupportedException">The stream does not support writing. </exception>
        /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
        public void Write(byte[] buffer, int offset, int count)
        {
            if (!FileInfo.IsOpenForWriting)
            {
                throw new NotSupportedException("The stream does not support writing.");
            }

            // checking length
            if (Length < Position + count)
            {
                Length = Position + count;
            }

            // performing physical write
            _physicalStream.Position = _fileTable.DataStartOffset + FileInfo.Start + Position;
            _physicalStream.Write(buffer, offset, count);

            Position += count;
            FileInfo.TimeModified = DateTime.Now;
        }

        /// <summary>
        /// Gets the length in bytes of the stream.
        /// </summary>
        /// <returns>
        /// An int value representing the length of the stream in bytes.
        /// </returns>
        /// <exception cref="T:System.NotSupportedException">A class derived from Stream does not support seeking. </exception>
        /// <exception cref="T:System.ObjectDisposedException">Methods were called after the stream was closed. </exception>
        public int Length
        {
            get
            {
                return FileInfo.Length;
            }
            set
            {
                if (!FileInfo.IsOpenForWriting)
                {
                    throw new NotSupportedException("The stream does not support writing.");
                }

                if (FileNode.Next == null)
                {
                    // if this is the last file, then we just might need to increase the physical length
                    long newPhysicalLength = _fileTable.DataStartOffset + FileInfo.Start + value;
                    if(_physicalStream.Length < newPhysicalLength)
                        _physicalStream.SetLength(newPhysicalLength);
                }
                else
                {
                    // if the new data doesn't fit betweeen current position and next file start
                    int spaceMissing = (FileInfo.Start + value) - FileNode.Next.Value.Start;
                    if (spaceMissing > 0)
                    {
                        // if the missing space is less than current file length
                        // and next file is smaller than current file
                        if 
                        (
                            (spaceMissing < FileInfo.Length)
                            &&
                            (FileNode.Next.Value.Length < FileInfo.Length)
                        )
                        {
                            // then we'd better move some next files to the end
                            MoveNextFilesToTheEnd(spaceMissing);
                        }
                        else
                        {
                            // otherwise it's easier to move the current file to the end
                            MoveFileToTheEnd();
                        }

                        Debug.Assert
                        (
                            (FileNode.Next == null)
                            ||
                            (FileInfo.Start + value <= FileNode.Next.Value.Start)
                        );
                    }
                }

                FileInfo.Length = value;
            }
        }

        /// <summary>
        /// Gets or sets the position within the current stream.
        /// </summary>
        /// <returns>
        /// The current position within the stream.
        /// </returns>
        public int Position { get; set; }

        /// <summary>
        /// Gets a value indicating whether the current stream supports reading.
        /// </summary>
        /// <returns>
        /// true if the stream supports reading; otherwise, false.
        /// </returns>
        public bool CanRead
        {
            get
            {
                return FileInfo.IsOpenForReading;
            }
        }

        /// <summary>
        /// Gets a value indicating whether the current stream supports writing.
        /// </summary>
        /// <returns>
        /// true if the stream supports writing; otherwise, false.
        /// </returns>
        public bool CanWrite
        {
            get
            {
                return FileInfo.IsOpenForWriting;
            }
        }

        /// <summary>
        /// Unblocks the opened file
        /// </summary>
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool disposing)
        {
            // Check to see if Dispose has already been called.
            if (_physicalStream != null)
            {
                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                if (disposing)
                {
                    // Dispose managed resources.
                    if (FileInfo != null)
                        FileInfo.Unblock();
                }

                // Call the appropriate methods to clean up
                // unmanaged resources here.
                // If disposing is false,
                // only the following code is executed.

                // Note disposing has been done.
                _fileNode = null;
                FileInfo = null;
                _fileTable = null;
                _physicalStream = null;
            }
        }

        
        private void MoveNextFilesToTheEnd(int spaceMissing)
        {
            FsDisk.MoveNextFilesToTheEnd(FileNode.Next, spaceMissing, _physicalStream, _fileTable);
        }

        private void MoveFileToTheEnd()
        {
            Debug.Assert(FileNode.Next != null);

            // copying physical data
            //TODO: implement some alighning
            int newStart = _fileTable.FileList.Last.Value.End + FsFileTable.ReservedSpaceForGrowing;
            FsDisk.CopyData
            (
                FileInfo.Start, 
                FileInfo.Length, 
                newStart,
                _physicalStream,
                _fileTable.DataStartOffset
            );

            // moving FileNode to the end
            //TODO: this might be inefficient, as it needs to iterate through list - better try to just to switch node pointers
            _fileTable.FileList.Remove(FileNode);
            _fileTable.FileList.AddLast(FileNode);
            Debug.Assert(FileNode.Previous != null);

            FileInfo.Start = newStart;
        }
    }
}
